package com.example.finalwork2.component;

import com.example.finalwork2.entity.AlertLevel;
import com.example.finalwork2.entity.Rule;
import com.example.finalwork2.mapper.IAlertLevelMapper;
import com.example.finalwork2.mapper.RuleMapper;
import jakarta.annotation.PostConstruct;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class SignalRuleManager {

    private final RuleMapper ruleMapper;
    private final IAlertLevelMapper alertLevelMapper;

    // key示例格式： ruleNo|batteryType|signalType
    private final Map<String, List<AlertLevel>> ruleMap = new ConcurrentHashMap<>();

    public SignalRuleManager(RuleMapper ruleMapper, IAlertLevelMapper alertLevelMapper) {
        this.ruleMapper = ruleMapper;
        this.alertLevelMapper = alertLevelMapper;
    }

    @PostConstruct
    public void init() {

        ruleMap.clear();

        // 1. 查询所有规则
        List<Rule> rules = ruleMapper.selectList(null);

        // 2. 遍历每个规则，查出对应的报警等级列表
        for (Rule rule : rules) {
            List<AlertLevel> alertLevels = alertLevelMapper.getByRuleId(rule.getId());
            String key = buildKey(rule.getRuleNo(), rule.getBatteryType(), rule.getSignalType());
            System.out.println(key);
            ruleMap.put(key, alertLevels);
        }
    }

    // 构造唯一key，方便查找
    private String buildKey(String ruleNo, String batteryType, String signalType) {
        return ruleNo + "|" + batteryType + "|" + signalType;

    }

    public List<AlertLevel> getRules(String ruleNo, String batteryType, String signalType) {
        String key = buildKey(ruleNo, batteryType, signalType);
        System.out.println(key);
        return ruleMap.getOrDefault(key, Collections.emptyList());
    }

    public void refresh() {
        init();
    }
}

